<template>
  <div class="member">
    <el-dialog
      title="成员管理"
      v-model="dialogTransfer"
      style="max-width: 900px !important; min-width: 790px !important"
      width="90vw"
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeDialogTransferClick"
    >
      <div>
        <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
          <el-tab-pane label="搜索" name="search"></el-tab-pane>
          <el-tab-pane label="用户" name="tabOne"></el-tab-pane>
          <!-- <el-tab-pane label="岗位" name="tabTwo"></el-tab-pane> -->
          <el-tab-pane label="角色" name="tabThree" v-if="showRole"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="transferBox">
        <!-- 搜索出现 -->
        <div v-if="activeName == 'search'" class="transfer_left">
          <div style="width: 100%">
            <div class="searchinput">
              <el-input v-model="searchInput" style="width: 300px" @keyup.enter="searchUserClick" placeholder="请输入要搜索的成员名称"> </el-input>
              <el-button :icon="Search" @click="searchUserClick">搜索</el-button>
            </div>

            <div>
              <el-table :data="searchUserList" style="width: 100%" v-loading="searchUserLoading" @row-dblclick="deptPersonRowDbClick">
                <el-table-column prop="nickName" label="昵称">
                  <template #default="scope">
                    <i class="el-icon-user-solid icon_size icon_user"></i>
                    <span>{{ scope.row.nickName }}</span>
                  </template>
                </el-table-column>

                <el-table-column prop="dept" label="部门" width="">
                  <template #default="scope">
                    <!-- <span v-if="scope.row.dept">{{ scope.row.dept.name }}</span> -->
                    <span v-if="scope.row.deptName">{{ scope.row.deptName }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <div v-else class="transfer_left">
          <div v-if="activeName == 'tabOne'" class="left_left">
            <el-tree :data="deptDatas" :load="getDeptDatas" :props="defaultProps" :expand-on-click-node="false" lazy @node-click="handleNodeClick">
              <template #default="{ node, data }">
                <span @dblclick="handleNodeDblClick(node, data)">{{ node.label }}</span>
              </template>
            </el-tree>
          </div>
          <div v-if="activeName != 'tabOne'" class="left_left">
            <div class="jobName" :class="jobActive == i ? 'jobActive' : ''" v-for="(v, i) in jobList" :key="i" @click="tabTwoNameClick(v, i)">
              {{ v.name }}
            </div>
          </div>
          <div class="left_right">
            <el-table :data="deptPersonList" v-loading="deptLoading" @row-dblclick="deptPersonRowDbClick">
              <el-table-column prop="nickName" label="昵称" width="100">
                <template #default="scope">
                  <i class="el-icon-user-solid icon_size icon_user"></i>
                  <span>{{ scope.row.nickName }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="dept" label="部门" width="">
                <template #default="scope">
                  <!-- <span v-if="scope.row.dept">{{ scope.row.dept.name }}</span> -->
                  <span v-if="scope.row.deptName">{{ scope.row.deptName }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div class="transfer_center">
          <el-button type="primary" :icon="DArrowRight" :disabled="deptPersonList.length == 0" @click="allrightClick"></el-button>
        </div>
        <div class="transfer_right" style="">
          <el-table :data="TeamPersonList">
            <el-table-column prop="nickName" label="昵称">
              <template #default="scope">
                <span v-if="scope.row.userId">
                  <el-icon class="icon_size icon_user"><Avatar /></el-icon>
                  <!-- <i class="el-icon-user-solid icon_size icon_user"></i> -->
                  <span>{{ scope.row.nickName }}</span>
                </span>

                <span v-else>
                  <el-icon class="icon_size icon_building"><OfficeBuilding /></el-icon>
                  <!-- <i class="el-icon-office-building icon_size icon_building"></i> -->
                  <span>{{ scope.row.label }}</span>
                </span>
              </template>
            </el-table-column>

            <!-- <el-table-column v-if="IsRole" prop="dept" label="权限">
              <template #default="scope">
                <el-select
                  v-model="scope.row.RoleValues"
                  multiple
                  placeholder="请选择"
                  collapse-tags
                  class="transfer_Right_perm"
                  @change="RoleValuesChange(scope.row)"
                >
                  <el-option v-for="items in roleList" :key="items.value" :label="items.label" :value="items.value"></el-option>
                </el-select>
              </template>
            </el-table-column> -->

            <!-- <el-table-column prop="dept" width="40"> -->
            <el-table-column prop="dept" width="40">
              <template #default="scope">
                <div>
                  <!-- <el-tooltip v-if="IsRole" class="item" effect="dark" content="全选" placement="top">
                    <el-icon @click="roleValueAllClick(scope.row)"><Check /></el-icon>
                  </el-tooltip> -->
                  <el-tooltip class="item" effect="dark" content="删除" placement="top">
                    <el-icon class="closeColor" @click="deptDeletePersonClick(scope.row)"><Close /></el-icon>
                    <!-- <i class="el-icon-close closeColor" @click="deptDeletePersonClick(scope.row)"></i> -->
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="memberLoading" @click="closeDialogTransferClick">取 消</el-button>
          <el-button :disabled="memberLoading" type="primary" @click="sureDialogTransferClick">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// import teamApi from '@/api/documents/teamApi.js';
// import yuDeptMemberApi from '@/api/documents/yuDeptMemberApi.js';
// import { apiDeptQueryFreePerm, apiUsersQueryFreePerm } from '@/api/system/dept';
import { ApiPerDeptFreePerm, ApiPerUserFreePerm } from '@/api/personDoc/personDocApi';

import { Search, DArrowRight } from '@element-plus/icons-vue';
const emit: any = defineEmits(['sureDialogTransferClick']);
const props = defineProps({
  IsRole: {
    //是否显示权限
    type: Boolean,
    default: true
  },

  isClick: {
    type: Boolean,
    default: true
  },

  showRole: {
    type: Boolean,
    default: true
  }
});
const treeNodeList = ref([]);
const memberLoading = ref(false);
const activeName = ref('tabOne');
const dialogTransfer = ref(false);
const deptDatas = ref([]); //左边部门
const deptPersonList = ref([]);
const defaultProps = reactive({
  children: 'children',
  label: 'deptName',
  isLeaf: 'leaf'
});
const TeamPersonList = ref([]);
const roleList: any = ref(['preview']);
const fileRoleList = reactive([
  { label: '下载', value: 'download' },
  { label: '预览', value: 'preview' },
  { label: '编辑', value: 'editor' },
  { label: '删除', value: 'remove' },
  { label: '打印', value: 'print' },
  { label: '复制', value: 'copy' },
  { label: '移动', value: 'move' },
  { label: '重命名', value: 'rechristen' }
]);

const folderRoleList = ref([
  { label: '新建', value: 'newBuilt' },
  { label: '上传', value: 'upload' },
  { label: '预览', value: 'preview' },
  { label: '删除', value: 'remove' },
  { label: '复制', value: 'copy' },
  { label: '移动', value: 'move' },
  { label: '重命名', value: 'rechristen' }
]);
const deptLoading = ref(false);
const jobList = ref([]); //保存岗位

const jobActive = ref(null);
const searchInput = ref(''); //搜索
const searchUserLoading = ref(false);
const searchUserList = ref([]);

// 搜索
const searchUserClick = () => {
  searchUserLoading.value = true;
  ApiPerUserFreePerm({
    nickName: searchInput.value,
    enabled: 1
  })
    .then((res) => {
      res.data.rows.forEach((item) => {
        item.typeId = item.userId;
      });
      searchUserList.value = res.data.rows;

      searchUserLoading.value = false;
    })
    .catch((err) => {
      searchUserLoading.value = false;
    });
};

// tab标签切换
const handleTabClick = () => {
  deptPersonList.value = [];
  if (activeName.value == 'search') {
  }
  if (activeName.value == 'tabOne') {
  }
  if (activeName.value == 'tabTwo') {
    jobActive.value = null;
    jobList.value = [];
    apiJobQueryUnlimited();
  }
  if (activeName.value == 'tabThree') {
    jobActive.value = null;
    jobList.value = [];
    apiRolesAllUnlimited();
  }
};

// 获取岗位
const apiJobQueryUnlimited = () => {
  // let params = {};
  // yuDeptMemberApi.apiJobQueryUnlimited(params).then((res) => {
  //   this.jobList = res;
  // });
};

// 获取角色
const apiRolesAllUnlimited = () => {
  // yuDeptMemberApi.apiRolesAllUnlimited().then((res) => {
  //   this.jobList = res;
  // });
};

// 获取岗位成员(无权限限制)
const apiUsersGetUserByJob = (id) => {
  // yuDeptMemberApi
  //   .apiUsersGetUserByJob({
  //     id: id
  //   })
  //   .then((res) => {
  //     res.forEach((item) => {
  //       item.userId = item.id;
  //     });
  //     this.deptPersonList = res;
  //   });
};

// 获取角色成员(无权限限制)
const apiUsersGetUserByRole = (id) => {
  // yuDeptMemberApi
  //   .apiUsersGetUserByRole({
  //     id: id
  //   })
  //   .then((res) => {
  //     res.forEach((item) => {
  //       item.userId = item.id;
  //     });
  //     this.deptPersonList = res;
  //   });
};

// 点击岗位
const tabTwoNameClick = (v, i) => {
  // this.jobActive = i;
  // if (this.activeName == 'tabTwo') {
  //   this.apiUsersGetUserByJob(v.id);
  // }
  // if (this.activeName == 'tabThree') {
  //   this.apiUsersGetUserByRole(v.id);
  // }
};

// 获取左侧部门数据
const getDeptDatas = (node, resolve) => {
  const sort = 'id,desc';
  const params = { sort: sort };
  if (typeof node !== 'object') {
    if (node) {
      params['name'] = node;
    }
  } else if (node.level !== 0) {
    params['parentId'] = node.data.deptId;
  }
  setTimeout(() => {
    ApiPerDeptFreePerm(params).then((res) => {
      console.log('🚀 ~ 获取左侧部门数据 ~ res:', res);

      res.data.forEach((item) => {
        item.typeId = item.deptId;
        item.perm = 0;
      });
      if (resolve) {
        resolve(res.data);
      } else {
        deptDatas.value = res.data;
      }
    });
  }, 100);
};

// 切换部门
const handleNodeClick = async (data) => {
  console.log('handleNodeClick', data);

  let deptId = null;
  if (data.deptId === 0) {
    deptId = null;
  } else {
    deptId = data.deptId;
  }
  deptLoading.value = true;

  await ApiPerUserFreePerm({
    deptId: deptId,
    size: 10000,
    page: 0,
    enabled: 1,
    sort: 'id,desc'
    // teamId: '28'
  })
    .then((res) => {
      console.log('🚀 ~ 切换部门 ~ res:', res);

      res.data.rows.forEach((item) => {
        item.deptId = null;
        item.perm = 0;
        item.typeId = item.userId;
      });
      deptPersonList.value = res.data.rows;
      console.log(deptPersonList.value, '00000000000000000');

      deptLoading.value = false;
    })
    .catch((err) => {
      deptLoading.value = false;
    });
};

//双击左边树事件
const handleNodeDblClick = (node, data) => {
  return false;
  // if (this.isClick) {
  //   if (this.TeamPersonList.findIndex((item) => item.deptId == data.deptId) == -1) {
  //     this.TeamPersonList.push(data);
  //   }
  // } else {
  //   this.$message.warning('分享暂不支持选择部门哦~');
  // }
};

//双击左边部门表格
const deptPersonRowDbClick = (data) => {
  if (TeamPersonList.value.findIndex((item) => item.userId == data.userId) == -1) {
    TeamPersonList.value.push(data);
  }
};

// 全部成员到右边
const allrightClick = () => {
  deptPersonList.value.forEach((item) => {
    deptPersonRowDbClick(item);
  });
};

// 关闭成员穿梭框
const closeDialogTransferClick = () => {
  dialogTransfer.value = false;
  memberLoading.value = false;
  TeamPersonList.value = [];
};

// 权限全选
const roleValueAllClick = (row) => {
  // row.RoleValues = this.roleList.map((item) => {
  //   return item.value;
  // });
  // // console.log(row.RoleValues)
};

// 删除穿梭框右边成员
const deptDeletePersonClick = (val) => {
  TeamPersonList.value.forEach((item, index) => {
    if (item.userId && item.userId == val.userId) {
      TeamPersonList.value.splice(index, 1);
    }
  });
};

// 权限选择
const RoleValuesChange = (val) => {
  // console.log(val)
  // if(val.RoleValues.includes('download')){
  // 	val.download=1
  // }else{
  // 	val.download=0
  // }
  // if(val.RoleValues.includes('preview')){
  // 	val.preview=1
  // }else{
  // 	val.preview=0
  // }
  // if(val.RoleValues.includes('editor')){
  // 	val.editor=1
  // }else{
  // 	val.editor=0
  // }
  // if(val.RoleValues.includes('upload')){
  // 	val.upload=1
  // }else{
  // 	val.upload=0
  // }
};

const sureDialogTransferClick = () => {
  memberLoading.value = true;
  // console.log(this.TeamPersonList, "this.TeamPersonList");
  emit('sureDialogTransferClick', TeamPersonList.value);
};

// 打开分发对话框
//  openDistributeYu(arr) {
//       this.treeNodeList = arr
//       this.$refs.yuDeptMember._data.dialogTransfer = true;
//     },
const openDialog = (val) => {
  treeNodeList.value = [];
  dialogTransfer.value = true;
};

defineExpose({
  //调用组件需要导出 v-model的变量
  openDialog,
  dialogTransfer,
  TeamPersonList,
  sureDialogTransferClick
});
</script>

<style scoped lang="scss">
::deep(.el-dialog) {
  max-width: 900px !important;
  min-width: 790px !important;
}

:deep(.el-dialog__body) {
  padding: 0 20px 20px;
}

:deep(.el-tabs) {
  margin-bottom: 0;
}

.transferBox {
  display: flex;
  justify-content: space-between;

  .searchinput {
    display: flex;
  }

  .transferGloab {
    height: 400px;
    border: 1px solid #f1f1f1;
    overflow-y: auto;
    overflow-x: auto;
    padding: 6px;
  }

  .transfer_left {
    @extend .transferGloab;
    width: 450px;
    min-width: 450px;
  }

  .transfer_right {
    @extend .transferGloab;
    width: 320px;
    min-width: 320px;
  }

  .transfer_Right_perm {
    width: 100%;

    :deep(.el-input__inner) {
      border: 0px !important;
    }
  }

  .transfer_left {
    display: flex;
    justify-content: space-between;

    .left_left {
      height: 385px;
      overflow: auto;
      width: 230px;
    }

    .left_right {
      height: 380px;
      width: 200px;
      min-width: 40%;
      border-left: 1px solid #f1f1f1;
      overflow: auto;
      div {
        padding: 8px;
      }
    }

    .jobName {
      color: #606266;
      font-size: 14px;
      margin-bottom: 4px;
      padding: 4px 6px;
      border-radius: 3px;
      cursor: pointer;
    }

    .jobActive {
      background-color: #f5f7fa;
    }
  }

  .transfer_right {
    // width: 30%;
    // min-width: 360px;
    // max-width: 55%;
  }

  .icon_size {
    font-size: 15px;
  }

  .icon_user {
    color: #36a3f7;
  }

  .icon_building {
    color: #f2951c;
  }

  .transfer_center {
    height: 400px;
    line-height: 400px;
    text-align: center;
    font-size: 26px;
  }

  .closeColor {
    margin-top: 6px;
    font-size: 16px;
    cursor: pointer;
  }

  .closeColor:hover {
    color: #f56c6c;
  }
}
</style>
